#include "userconfigs.h"
#include <QFile>
#include "log/cnslogger.h"
#include "cnsGlobal.h"

UserConfigs::UserConfigs()
{

}


QString UserConfigs::getValueFromUserConfigs(const QString &key)
{
    auto it = s_userConfigs.find(key);
    if(it == s_userConfigs.end())
    {
        return QString();
    }
    return it.value();
}

void UserConfigs::setUserConfig(const QString &key, const QString &value)
{
    s_userConfigs[key] = value;
}

void UserConfigs::loadConfigFile()
{
    QFile file("config/user.ini");
    if(file.open(QIODevice::ReadOnly)){
        QString data = file.readAll();
        QStringList kvs = data.split('\n', QString::SkipEmptyParts);
        for(QStringList::iterator it = kvs.begin(); it != kvs.end(); it ++)
        {
            QStringList kv = it->split(':', QString::SkipEmptyParts);
            if(kv.size() != 2)
            {
                CNSLOG_ERROR(QString("config file format error in block %1!").arg(*it));
                continue;
            }
            s_userConfigs[kv[0]] = kv[1];
        }
        file.close();
    }
}

void UserConfigs::saveConfigFile()
{
    QFile file("config/user.ini");
    if(file.open(QIODevice::WriteOnly)){
        QString data;
        for(auto it = s_userConfigs.begin(); it != s_userConfigs.end(); it++)
        {
            data += it.key();
            data += ':';
            data += it.value();
            data += '\n';
        }
        file.write(data.toLatin1(), data.size());
        file.close();
    }
}

CNS_INIT(UserConfigs)
CNS_REGISTER_COM_FACTORY(UserConfigs)
CNS_INIT_END
